<?php
class Pageley_Basic_Command_Save extends Pageley_Controller_Command_TransactionalReadWrite {

	private $id;
	private $typeName;

	public function setId($id) {
		$this->id = $id;
	}

	public function setTypeName($typeName) {
		$this->typeName = $typeName;
	}

	protected function executeInternal() {
		$unitOfWork = $this->getUnitOfWork();
        $factory = Pageley_Config::getInstance();
		$type = $factory->valueOf("type." . $this->typeName);
        $model = new Pageley_Util_ArrayMap();
        $entity = null;
        $serializer = Pageley_Serializer_Format::$HTTP->getSerializer();
        if($this->id != null) {
            $entity = $unitOfWork->find($type, $this->id);
            if($entity === null) {
                throw new Pageley_Controller_RuntimeException("Cannot update entity. Entity with id " . $this-id . " does not exist.");
            }
            $serializer->deserializeInto($this->getProperties(), $entity);
        } else {
            $entity = $serializer->deserialize($this->getProperties(), $type);
        }
        $unitOfWork->register($entity);
		$model->put("entity", $entity);
		return new Pageley_Controller_ModelAndView($model);
	}
}